package net.vsame.url2sql.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.Properties;

/**
 * Jar包相关工具
 * 
 * @author <a href="mailto:gaollg@sina.com">gaollg@sina.com</a>
 *
 */
public class JarUtils {

	/**
	 * null 表示在ClassPath下
	 * @param clazz
	 * @return
	 */
	public static String getJarPath(Class<?> clazz){
		String path = '/' + clazz.getName().replace('.', '/') + ".class";
		URL u = JarUtils.class.getResource(path);
		if(!"jar".equalsIgnoreCase(u.getProtocol())){
			return null;
		}
		String file = u.getFile();
		return file.substring(0, file.length()-path.length()-2);
	}
	
	/**
	 * 取得class所在 jar包名称
	 * 
	 * @param clazz 
	 * @return 返回值为null 表示直接在classpath下
	 */
	public static String getJarName(Class<?> jarClazz){
		String file = getJarPath(jarClazz);
		if(file == null){
			//就在classpath下
			return null;
		}
		return new File(file).getName();
	}
	
	/**
	 * 取得class所在 jar包 中的资源
	 * 
	 * @param jarClazz 
	 * @param resource 所取的资源
	 * @return
	 */
	public static URL getResourceFromJar(Class<?> jarClazz, String resource){
		String file = getJarPath(jarClazz);
		if(file == null){
			//就在classpath下
			return getResourceFromClassPath(resource);
		}
		
		if(resource.startsWith("/")){
			resource = resource.substring(1);
		}
		
        try {
			Enumeration<URL> res = jarClazz.getClassLoader().getResources(resource);
			while (res.hasMoreElements()) {
				URL url = res.nextElement();
				if(url.getFile().startsWith(file)){
					return url;
				}
			}
		} catch (IOException e) {
			//IO异常直接返回 null
			return null;
		}
		return null;
	}
	
	/**
	 * 取得class所在 jar包 中的资源
	 * 
	 * @param jarClazz 
	 * @param resource 所取的资源
	 * @return
	 */
    public static InputStream getResourceAsStreamFromJar(Class<?> jarClazz, String resource){
		URL url = getResourceFromJar(jarClazz, resource);
		try {
		    return url != null ? url.openStream() : null;
		} catch (IOException e) {
		    return null;
		}
    }
    
	public static URL getResourceFromClassPath(String resource){
		if(!resource.startsWith("/")){
			resource = "/" + resource;
		}
		return JarUtils.class.getResource(resource);
	}
	
    /**
     * 取得class所在 jar包 中的资源
     * 
     * @param jarClazz 
     * @param resource 所取的资源
     * @return
     */
    public static InputStream getResourceAsStreamFromClassPath(String resource){
    	URL url = getResourceFromClassPath(resource);
    	try {
    		return url != null ? url.openStream() : null;
    	} catch (IOException e) {
    		return null;
    	}
    }
    
    /**
     * 取得InputStream
     * @param in
     * @return
     */
    public static Properties loadProperties(InputStream in) {
    	if(in == null){
    		return null;
    	}
    	
    	Properties properties = new Properties();
    	try {
			try {
				properties.load(in);
			} finally {
				in.close();
			}
		} catch (IOException e) {
		}
    	return properties;
    }
    
	/**
	 * 取得文件的所有文本内容 
	 * @param file
	 * @return
	 */
	public static String readAllText(InputStream in){
		StringBuffer sb = new StringBuffer();
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		try {
			String tempString = null;
			while ((tempString = br.readLine()) != null) {
				sb.append(tempString).append("\r\n");
            }
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally{
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
	
	public static String readInputStream(Charset charset, InputStream in) {
		byte[] bytes = new byte[1024];
		int length = -1;
		ByteArrayOutputStream byteOutput= new ByteArrayOutputStream();
		try {
			while ((length = in.read(bytes)) != -1) {
				byteOutput.write(bytes, 0, length);
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return new String(byteOutput.toByteArray(), charset);
	}
	
	public static String readResourceFromJar(Charset charset, Class<?> jarClazz, String resource) {
		InputStream in = getResourceAsStreamFromJar(jarClazz, resource);
		return readInputStream(charset, in);
	}
	
	public static String readResourceFromJar(Class<?> jarClazz, String resource) {
		return readResourceFromJar(Charset.forName("utf-8"), jarClazz, resource);
	}
	
	/*
	public static void main(String[] args) {
		System.out.println(getJarPath(WorkModel.class));
		System.out.println(getJarName(WorkModel.class));
		
		System.out.println("------------");
		System.out.println(getJarPath(JarUtils.class));
		System.out.println(getJarName(JarUtils.class));
		
		System.out.println(readResourceFromJar(WorkModel.class, "META-INF/MANIFEST.MF"));
	}
	*/
	
}
